package com.tich.order.listener;

import cn.hutool.core.bean.BeanUtil;
import com.tich.constant.RabbitMqConstant;
import com.tich.enumration.OrderStatus;
import com.tich.order.domain.entity.Orders;
import com.tich.order.domain.entity.OrdersDeleted;
import com.tich.order.mapper.OrderDeletedMapper;
import com.tich.order.mapper.OrderMapper;
import com.tich.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OrderListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private OrderDeletedMapper orderDeletedMapper;

    /**
     * 检查订单是否已支付
     * @param id
     * */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMqConstant.ORDER_PAY_DELAY_QUEUE),
            exchange = @Exchange(name = RabbitMqConstant.ORDER_DELAY_DIRECT, type = ExchangeTypes.DIRECT, delayed = "true"),
            key = {RabbitMqConstant.ORDER_PAY_DELAY_KEY}
    ))
    public void OrderPayDelayListen(Long id){
        log.info("订单建立已经15分钟查看是否支付，{}", id);
        //1.查看本地订单状态是否已支付
        Orders orders = orderMapper.selectById(id);
        if(orders == null || orders.getOrderStatus() != OrderStatus.UNPAID.getCode()){
            //已支付则直接返回
            return;
        }
        //2.如果订单未支付则取消订单，恢复库存
        iOrderService.cancelOrder(id);
    }

    /**
     * 删除订单
     * @param orders
     * */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMqConstant.ORDER_DELETE_QUEUE),
            exchange = @Exchange(name = RabbitMqConstant.ORDER_DIRECT),
            key = {RabbitMqConstant.ORDER_DELETE_KEY}
    ))
    public void orderDeleteListener(Orders orders){
        log.info("将删除的订单信息插入数据库：{}", orders);
        OrdersDeleted ordersDeleted = BeanUtil.copyProperties(orders, OrdersDeleted.class);
        orderDeletedMapper.insert(ordersDeleted);
    }

}
